<ul id="error">
</ul>
<table>
    <form name="products">
    <tr>
        <th><a id="save" href="#">save</a></th>
        <th><?= $title ?></th>
    </tr>
    <tr>
        <td>Название</td>
        <td><input type="text" name="name" value="<?= Arr::get($product, 'name') ?>"/></td>
    </tr>
    <tr>
        <td>Ссылка</td>
        <td><input type="text" name="href" value="<?= Arr::get($product, 'href') ?>"/></td>
    </tr>
    <tr>
        <td>Тип</td>
        <td><input type="text" name="type" value="<?= Arr::get($product, 'type') ?>"/></td>
    </tr>
    <tr>
        <td>Пол</td>
        <td><input type="text" name="sex" value="<?= Arr::get($product, 'sex') ?>"/></td>
    </tr>
    <tr>
        <td>Размер</td>
        <td><input type="text" name="size" value="<?= Arr::get($product, 'size') ?>"/></td>
    </tr>
    <tr>
        <td>Длина</td>
        <td><input type="text" name="width" value="<?= Arr::get($product, 'width') ?>"/></td>
    </tr>
    <tr>
        <td>Высота</td>
        <td><input type="text" name="height" value="<?= Arr::get($product, 'height') ?>"/></td>
    </tr>
    <tr>
        <td>Описание товара</td>
        <td><textarea  name="content"><?= Arr::get($product, 'content') ?></textarea></td>
    </tr>
    <tr>
        <td>Комплектация</td>
        <td><textarea  name="complectation"><?= Arr::get($product, 'complectation') ?></textarea></td>
    </tr>   
    <tr>
        <td>Цена</td>
        <td><input type="text" name="price" value="<?= Arr::get($product, 'price') ?>"/></td>
    </tr>
    <tr>
        <td>Количество</td>
        <td><input type="text" name="quantity" value="<?= Arr::get($product, 'quantity') ?>"/></td>
    </tr>
    <tr>
        <td>Ключевые слова</td>
        <td><textarea name="html_keyword"><?= Arr::get($product, 'html_keyword') ?></textarea></td>
    </tr>
    <tr>
        <td>Описание</td>
        <td><textarea name="html_description"><?= Arr::get($product, 'html_description') ?></textarea></td>
    </tr>
    <tr id="images_uploader">
        
    </tr>
    
    <input type="hidden" name="id" value="<?= Arr::get($product, 'id', '')?>">
    <input type="hidden" name="catalogue_id" value="<?= Arr::get($product, 'catalogue_id', '')?>">
    </form>
</table>

<script type="text/javascript">
    var product_id = <?= Arr::get($product, 'id', 0)?>;
    var catalogue_id = <?= Arr::get($product, 'catalogue_id', '')?>;
    
    function load_product_images(){
        $.ajax({url:'/admin/catalogue/product_images',
                type:'POST',
                data: {'id' : product_id},
                timeout: 5000,
                success: function(k){                    
                    var response = eval("(" + k + ")");
                    $('#images_line').empty();
                    $('#images_line').height((response.length) ? <?= Kohana::$config->load('products.image_min_height')+12?> : 0);
                    $('#images_line').width(<?= Kohana::$config->load('products.image_min_width')+12?> * response.length);
                    for(var key in response){
                        $('#images_line').append('<div class="image_box">' + 
                                                    '<img src="'+response[key]+'"/>'+
                                                    '<span class="image_delete">X</span>'+
                                                 '</div>');
                    }
                    
                },
                error: function(){
                    alert('Ошибка обращения к серверу');
                }
        });
    }
    
    $(document).ready(function(){
        
        var uploader = new qq.FileUploader({
                element: document.getElementById('images_uploader'),
                action: '/admin/catalogue/product_image_upload',
                debug: false,
                params: {'id' : product_id},
                template: '<td><div class="qq-upload-button">Изображения</div></td>'+
                          '<td>'+
                          '<div id="images_box">'+
                          '<div id="images_line"></div>'+                          
                          '<div class="qq-upload-drop-area"><span>Перетащите файлы изображений для загрузки</span></div>' +
                          '</div>' +
                          '<ul class="qq-upload-list"></ul>' + 
                          '</td>',
                onComplete: function(id, filename, responseJSON){
                    $(".qq-upload-list").find("li[file_id="+id+"]").remove();
                    load_product_images();
                }
            }); 
           
        
	var cache = {};
        var lastXhr;
        $("input[name='type'], input[name='sex'], input[name='size']").each(function(){ 
            var field = $(this).attr('name');
            cache[field] = {};
            $(this).autocomplete({ 
                        minLength: 0,
                        source: function( request, response ) {
                                    var term = request.term;
                                    if ( term in cache[field] ) {
					response( cache[field][term] );
					return;
                                    }
                                    
                                    var data = {'term':term,
                                                'table' : $('form').attr('name'),
                                                'field' : field};
                                            
                                    lastXhr = $.getJSON( '/admin/service/autocomplete', data, function( data, status, xhr ) {
					cache[field][term] = data;
					if ( xhr === lastXhr ) {
						response( data );
					}
                                    });
			}
            });
            
            $(this).bind('focus', function(){
                $(this).autocomplete("search");
            });

        });
        
        $('#save').bind('click', function(){
            $('#error').empty().slideUp();
            
            var data = {};
            $('#content table').find('input, textarea').each(function(){                
                key = $(this).attr('name');                
                value = $(this).val();
                data[key] = value;
            });
            
            $.ajax({'url':'/admin/catalogue/product_save',
                    'type': 'POST',
                    'data': data,
                    'timeout':5000,
                    'success':function(k){
                        response = eval("(" + k + ")");
                        if(response.status == 'ok')
                            window.location.assign("/admin/catalogue/product?id=" + catalogue_id)
                        else {                            
                            var error = response.error;
                            $('#error').append('Ой, ошибочка вышла...<br/>');
                            for(var key in error){
                                $('#error').append('<li>' + error[key] + '</li>');             
                            }
                            $('#error').slideDown();
                        }   
                    },
                    'error':function(){
                        alert('Ошибка!');
                    }
            });

           return false;
        }); 
        
       $(".image_delete").live('click', function(){
             var src = $(this).prev().attr('src');

            $.ajax({url: '/admin/catalogue/product_image_delete',
                    type: 'POST',
                    data: {'src': src},
                    success: function(){
                        load_product_images();
                    },
                    error: function(){
                        alert('Ошибка обращения к серверу');
                    }
            });
       });
        
    });
    
    $(window).load(function(e){
        $('#images_box').width($('#images_box').width());
        load_product_images();
    });

</script>